// active-reports.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    reportList: [],
    statusList: ['全部', '待审核', '已通过', '已拒绝'],
    statusIndex: 0,
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/active-reports/active-reports')) {
      return
    }
    
    this.loadActiveReports()
  },

  onShow() {
    this.refreshActiveReports()
  },

  // 加载主动报工列表
  loadActiveReports() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      limit: this.data.limit
    }
    
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusIndex - 1
    }
    
    api.getActiveReports(params).then(res => {
      const newList = this.data.page === 1 ? res.data.list : [...this.data.reportList, ...res.data.list]
      
      // 格式化时间
      newList.forEach(item => {
        item.createtime_text = this.formatTime(item.createtime)
      })
      
      this.setData({
        reportList: newList,
        hasMore: res.data.list.length === this.data.limit,
        loading: false
      })
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载主动报工列表失败:', err)
    })
  },

  // 刷新主动报工列表
  refreshActiveReports() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadActiveReports()
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadActiveReports()
    }
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value,
      page: 1,
      hasMore: true
    })
    this.loadActiveReports()
  },

  // 跳转到主动报工详情
  goToActiveReportDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/active-report-detail/active-report-detail?id=${id}`
    })
  },

  // 审核主动报工
  auditActiveReport(e) {
    if (!this.hasPermission('active_report_manage', 'audit')) {
      wx.showToast({
        title: '您没有审核权限',
        icon: 'none'
      })
      return
    }
    
    const id = e.currentTarget.dataset.id
    const status = e.currentTarget.dataset.status
    e.stopPropagation()
    
    let title = status == '1' ? '确认通过该主动报工？' : '确认拒绝该主动报工？'
    
    wx.showModal({
      title: '确认审核',
      content: title,
      success: (res) => {
        if (res.confirm) {
          this.submitActiveAudit(id, status)
        }
      }
    })
  },

  // 提交主动报工审核
  submitActiveAudit(reportId, status) {
    const data = {
      report_id: reportId,
      status: parseInt(status)
    }
    
    if (status == '2') {
      // 如果是拒绝，需要输入原因
      wx.showModal({
        title: '拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: (res) => {
          if (res.confirm) {
            data.audit_reason = res.content || ''
            this.doSubmitActiveAudit(data)
          }
        }
      })
    } else {
      this.doSubmitActiveAudit(data)
    }
  },

  // 执行主动报工审核提交
  doSubmitActiveAudit(data) {
    api.auditActiveReport(data).then(res => {
      wx.showToast({
        title: '审核成功',
        icon: 'success'
      })
      
      // 刷新列表
      this.refreshActiveReports()
    }).catch(err => {
      console.error('审核失败:', err)
      wx.showToast({
        title: err.msg || '审核失败',
        icon: 'none'
      })
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshActiveReports()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  },

  // 跳转到首页
  goToIndex() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 跳转到分配管理
  goToAllocationManage() {
    wx.navigateTo({
      url: '/pages/allocation-manage/allocation-manage'
    })
  },

  // 权限检查方法
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  },

  // 显示权限拒绝提示
  showPermissionDenied(module, action) {
    wx.showToast({
      title: `您没有${module}模块的${action}权限`,
      icon: 'none'
    })
  }
}) 